<template>
    <div>
      <!-- 面包屑导航区 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>学院管理</el-breadcrumb-item>
        <el-breadcrumb-item>班级列表</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 卡片视图区 -->
      <el-card>

        <!-- 搜索与添加区域-->
        <el-row>
          <!--专业列表-->
          <el-col :span="6">
            专业
            <el-cascader
              placeholder="请选择专业"
              v-model="queryInfo.majorId"
              :options="cascadeMajorList"
              :props="{ expandTrigger: 'hover'}"
              filterable
              clearable
              separator="--"
              :show-all-levels="false">
            </el-cascader>
          </el-col>
          <!--班级查询-->
          <el-col :span="6">
            班级
            <!--<el-input placeholder="请输入班级" v-model="queryInfo.className" class="input-with-select" clearable @clear="getStudentListLimit" style="width: 193px" ></el-input>-->
            <el-cascader
              placeholder="请选择班级"
              v-model="queryInfo.className"
              :options="cascadeClassList"
              :props="{ expandTrigger: 'hover'}"
              filterable
              clearable
              separator="--"
              :show-all-levels="false">
            </el-cascader>
          </el-col>
          <!--学号查询-->
          <el-col :span="6">
            学号
            <el-input placeholder="请输入学号" v-model="queryInfo.stuNumber" class="input-with-select" clearable @clear="getStudentListLimit" style="width: 193px" ></el-input>
          </el-col>
          <!--姓名查询-->
          <el-col :span="6">
            姓名
            <el-input placeholder="请输入姓名" v-model="queryInfo.stuName" class="input-with-select" clearable @clear="getStudentListLimit" style="width: 193px" ></el-input>
          </el-col>
        </el-row>
        <el-row>
          <!--楼栋列表-->
          <el-col :span="6">
            楼栋
            <el-select placeholder="请选择楼栋号" v-model="queryInfo.buildingId" clearable >
              <el-option
                v-for="item in buildingList"
                :key="item.buildingId"
                :label="item.buildingNumber"
                :value="item.buildingId">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="18" class="searchAndAdd">
            <el-button type="warning" icon="el-icon-search" @click="getStudentListLimit">搜索</el-button>
            <el-button type="primary" @click="addStudentDialogVisible = true">添加学生</el-button>
          </el-col>
        </el-row>

        <!-- 学生列表主体区域 -->
        <el-table :data="studentList" ref="tableRef" stripe >
          <el-table-column align="center" type="index" label="#"></el-table-column>
          <el-table-column align="center" prop="userName" label="学号"></el-table-column>
          <el-table-column align="center" prop="stuName" label="姓名"></el-table-column>
          <el-table-column align="center" prop="stuGender" label="性别">
            <template slot-scope="scope">
              <div v-if="scope.row.stuGender === 1">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-nan"></use>
                </svg>
              </div>
              <div v-else>
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-nv"></use>
                </svg>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="stuClass.className" label="班级"></el-table-column>
          <el-table-column align="center" label="操作" width="220px">
            <template slot-scope="scope">
              <!-- 编辑按钮 -->
              <span v-if="scope.row.dormitoryId < 1">
                 <el-button type="warning" icon="el-icon-edit" size="mini" @click="toggleExpand(scope.row)">未分配</el-button>
              </span>
              <span v-else>
                <el-button type="primary" plain  icon="el-icon-edit" size="mini" @click="toggleExpand(scope.row)">已分配</el-button>
              </span>
              <!-- 删除按钮 -->
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteStudent(scope.row)"></el-button>
            </template>
          </el-table-column>
          <!-- 展开列 -->
          <el-table-column type="expand" width="1">
            <template slot-scope="scope">
              <el-card class="expandCard">
                <el-form>
                  <table >
                    <tr>
                      <td><span class="labelText">学号</span></td>
                      <td>{{editStudentForm.userName}}</td>
                      <td width="100px"></td>
                      <td rowspan="3">
                        <el-image
                          style="width: 140px; height: 180px;
                            position: absolute; margin-top: -50%; margin-left: 35%"
                          :src="editStudentForm.stuImage"
                          fit="cover"
                          :preview-src-list="srcList">
                        </el-image>
                      </td>
                    </tr>
                    <tr>
                      <td><span class="labelText">姓名</span> </td>
                      <td><el-input prop="stuName" v-model="editStudentForm.stuName" clearable/></td>
                      <td></td>
                      <td></td>
                    </tr>
                    <tr>
                      <td><span class="labelText">身份证号</span> </td>
                      <td><el-input prop="stuIdentityCardNumber" v-model="editStudentForm.stuIdentityCardNumber" clearable /></td>
                      <td></td>
                      <td></td>
                    </tr>
                    <tr>
                      <td><span class="labelText">班级</span></td>
                      <td>
                        <el-cascader
                          placeholder="请选择班级"
                          prop="classId"
                          v-model="editStudentForm.classId"
                          :options="cascadeClassList"
                          :props="{ expandTrigger: 'hover'}"
                          filterable
                          separator="-">
                        </el-cascader>
                      </td>
                      <td></td>
                      <td rowspan="2">
                        <el-upload
                          style="margin-top: -27%; margin-left: 40%"
                          action="#"
                          ref="upload"
                          :auto-upload="false"
                          :on-change="uploadFormat">
                          <el-button size="small" type="primary" align="center">点击上传</el-button>
                          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1M</div>
                        </el-upload>
                      </td>
                    </tr>
                    <tr>
                      <td> <span class="labelText">宿舍</span></td>
                      <td>
                        <el-cascader
                          placeholder="请选择宿舍"
                          v-model="editStudentForm.stuBed"
                          :options="cascadeDormitoryList"
                          :props="{ expandTrigger: 'hover'}"
                          filterable
                          separator="-">
                        </el-cascader>
                      </td>
                      <td></td>
                      <td></td>
                    </tr>
                  </table>
                </el-form>
                <el-row></el-row>
                <el-row>
                  <el-col>
                    <span><el-button type="warning" size="small" icon="el-icon-edit" @click="cancelEdit" >取消</el-button></span>
                    <span><el-button type="primary" size="small" icon="el-icon-edit" @click="editStudent" >编辑</el-button></span>
                  </el-col>
                </el-row>
              </el-card>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[10, 20, 30, 100]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>

        <!-- 添加对话框 -->
        <el-dialog
          title="添加学生"
          :visible.sync="addStudentDialogVisible"
          width="50%"
          @close="addStudentDialogClosed">
          <!-- 内容主体区 -->
          <el-form class="addStudentForm" :model="addStudentForm" :rules="addStudentFormRules" ref="addStudentFormRef" label-width="100px">
            <el-form-item label="学号" prop="userName">
              <el-input v-model="addStudentForm.userName" clearable></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="stuName">
              <el-input v-model="addStudentForm.stuName" clearable></el-input>
            </el-form-item>
            <el-form-item label="身份证号码" prop="stuIdentityCardNumber">
              <el-input v-model="addStudentForm.stuIdentityCardNumber" clearable></el-input>
            </el-form-item>
            <el-form-item label="班级" prop="classId">
              <el-cascader
                placeholder="请选择班级"
                v-model="addStudentForm.classId"
                :options="cascadeClassList"
                :props="{ expandTrigger: 'hover',multiple:true}"
                filterable
                clearable
                separator="-">
              </el-cascader>
            </el-form-item>
            <el-form-item label="宿舍" prop="stuBed">
              <el-cascader
                placeholder="请选择宿舍"
                v-model="addStudentForm.stuBed"
                :options="cascadeDormitoryList"
                :props="{ expandTrigger: 'hover'}"
                filterable
                clearable
                separator="-">
              </el-cascader>
            </el-form-item>
            <el-form-item label="入住日期" prop="">
              <el-date-picker
                v-model="addStudentForm.stuIndate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="学生照片" prop="">
              <el-upload
                action="#"
                ref="upload"
                :auto-upload="false"
                :on-change="uploadFormat">
                <el-button size="small" type="primary">点击上传</el-button>
                <span slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png文件，且不超过2M</span>
              </el-upload>
            </el-form-item>
        </el-form>
          <!-- 底部区域 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="addStudentDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addStudent">确 定</el-button>
          </span>
        </el-dialog>


      </el-card>
    </div>
</template>

<script>
    export default {
        data() {
          return {
            /* 搜索信息 */
            queryInfo: {
              majorId: '',
              buildingId: '',
              stuNumber: '',
              stuName: '',
              className: '',
              pageNum: 1,
              pageSize: 10,
            },
            /* 分页total */
            total: 0,
            /*cascade专业列表数据*/
            cascadeMajorList: [],
            cascadeClassList: [],
            /*楼栋列表数据*/
            buildingList: [],
            /*宿舍列表数据*/
            cascadeDormitoryList: [],
            /*学生列表数据*/
            studentList: [],
            /* 添加对话框的显示/隐藏 */
            addStudentDialogVisible: false,
            /*图片预览*/
            srcList: [],
            /* 添加表单 */
            addStudentForm: {
              classId: [[1,1,1],[1,1,11]],
              dormitoryId: '',
              userName: '124324131',
              stuName: '积分来看待',
              stuIdentityCardNumber: '431225200011018090',
              stuBed: '',
              stuImage: '',
              stuIndate: '',
            },
            /* 添加表单验证规则对象 */
            addStudentFormRules: {
              userName: [
                {required: true, message: '请输入学生学号', trigger: 'blur'},
              ],
              stuName: [
                {required: true, message: '请输入学生姓名', trigger: 'blur'},
                {
                  pattern: /[\4E00-\u9FA5A-Za-z]{2,12}/,
                  message: '请输入长度在2-12个字符之间的中文名称', trigger: 'blur'
                }
              ],
              stuIdentityCardNumber:[
                {required: true, message: '请输入身份证号码', trigger: 'blur'},
                {
                  pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
                  message: '用户名长度在18个字符', trigger: 'blur'
                }
              ],
              classId:[
                {type: 'array', required: true, message: '请选择班级', trigger: 'blur'},
              ],
            },
            /* 编辑表单 */
            editStudentForm: {
              classId: '',
              dormitoryId: '',
              userName: '',
              stuName: '',
              stuIdentityCardNumber: '',
              stuBed: '',
              stuImage: '',
            },
            /* 取消提交编辑表单，重置数据 */
            resetEditStudentForm: {
              classId: '',
              dormitoryId: '',
              userName: '',
              stuName: '',
              stuIdentityCardNumber: '',
              stuBed: '',
              stuImage: '',
            },
          }
        },

      created() {
        this.getMajorAndBuildingList();
        this.getStudentListLimit();
      },

      methods: {
          /* 获取专业、楼栋列表数据*/
        async getMajorAndBuildingList() {
          //专业列表
          const {data: res} = await this.$axios.get(this.$http+'/collegeManageController/getMajorList').catch(err => {
            this.$message.error("专业列表数据请求失败");
          });
          //获取后台数据，重新复制给级联菜单
          let that = this;
          res.datas.majorList.forEach(function (item) {
            //专业列表框
            let collegeObj = { value: item.collegeId, label: item.collegeName, children: []};
            //班级列表框
            let classObj = { value: item.collegeId, label: item.collegeName, children: []};
            item.majorList.forEach(function (childrenItem) {
              let majorChildren1 = { value: childrenItem.majorId, label: childrenItem.majorName,};  //专业
              let majorChildren2 = { value: childrenItem.majorId, label: childrenItem.majorName, children: []}; //班级
              collegeObj.children.push(majorChildren1);
              classObj.children.push(majorChildren2);
              try {
                childrenItem.classList.forEach(function (classItem) {  //班级
                  if (classItem.classId === null)  //如果班级为空，跳过此次赋值
                    throw new Error("抛出异常跳出");
                  let classChildren = { value: classItem.classId, label: classItem.className};
                  majorChildren2.children.push(classChildren);
                })
              }catch (e) {}
            });
            that.cascadeMajorList.push(collegeObj);
            that.cascadeClassList.push(classObj);
          })
          //楼栋列表
          //发送请求 获取楼栋列表信息
          this.$axios.get(this.$http+'/buildingManageController/getBuildingIdList').then(res => {
            //楼栋列表
            this.buildingList = res.data.datas.buildingList;
            //宿舍列表
            let that = this;
            //遍历楼栋列表，设置value和label值
            res.data.datas.buildingList.forEach(function (item) {
              let buildings = {value: item.buildingId, label: item.buildingNumber, children: []}
              //遍历宿舍列表，设置值
              try {
                item.dormitoryList.forEach(function (childrenItem) {
                  if (childrenItem.dormitoryId === null) //如果寝室为空，跳过此次赋值
                    throw new Error("抛出异常跳出");
                    let dormitory = {value: childrenItem.dormitoryId, label: childrenItem.dormitoryRoom, children: []}
                  //再次遍历宿舍列表，设置床铺列表
                  item.dormitoryList.forEach(function (spendableItem) {
                    //宿舍号相等，则进行循环赋值给children
                    if (childrenItem.dormitoryId === spendableItem.dormitoryId){
                      for (let i = 1; i <= spendableItem.dormitorySpendable; i++){
                        let spendable = {value: i, label: i + '床'};
                        dormitory.children.push(spendable)
                      }
                    }
                  });
                  buildings.children.push(dormitory)
                })
              }catch (e) {}
              that.cascadeDormitoryList.push(buildings)
            })
            console.log(this.cascadeDormitoryList)
          }).catch(err => {
            this.$message.error("楼栋列表请求失败");
          });
        },

        /* 获取学生信息列表 */
        async getStudentListLimit() {
          if (typeof this.queryInfo.majorId  === 'undefined' )
            this.queryInfo.majorId = '';
          this.queryInfo.majorId = (this.queryInfo.majorId.length === 0) ? '' : this.queryInfo.majorId[1];
          this.queryInfo.className = (this.queryInfo.className.length === 0) ? this.queryInfo.className : this.queryInfo.className[2];
          const {data: res} = await this.$axios.get(this.$http+'/collegeManageController/getStudentListLimit',{
            params: this.queryInfo
          });
          this.studentList = res.datas.studentList;
          this.total = res.datas.total;
        },

        /* 展开列 手风琴效果 */
        toggleExpand(row) {
          //给图片预览属性赋值
          this.srcList[0] = row.stuImage;
          //编辑表单
          this.editStudentForm.classId = [row.stuClass.major.college.collegeId, row.stuClass.major.majorId, row.classId];
          this.editStudentForm.userName = row.userName;
          this.editStudentForm.stuName = row.stuName;
          this.editStudentForm.stuIdentityCardNumber = row.stuIdentityCardNumber;
          this.editStudentForm.stuBed = [row.dormitory === null ? 0 : row.dormitory.buildingId, row.dormitory === null ? 0 : row.dormitory.dormitoryId, row.stuBed];
          this.editStudentForm.stuImage = row.stuImage;

          //将编辑表单的值再赋给重置编辑表单
          this.resetEditStudentForm.classId = [row.stuClass.major.college.collegeId, row.stuClass.major.majorId, row.classId];
          this.resetEditStudentForm.userName = row.userName;
          this.resetEditStudentForm.stuName = row.stuName;
          this.resetEditStudentForm.stuIdentityCardNumber = row.stuIdentityCardNumber;
          this.resetEditStudentForm.stuBed = [row.dormitory === null ? 0 : row.dormitory.buildingId, row.dormitory === null ? 0 : row.dormitory.dormitoryId, row.stuBed];
          this.resetEditStudentForm.stuImage = row.stuImage;

          //手风琴效果
          let $table = this.$refs.tableRef;
          this.studentList.map((item) => {
            if (row.stuId !== item.stuId){
              $table.toggleRowExpansion(item, false);
              item.expansion =false;
            }else
              item.expansion = !item.expansion;
          })
          $table.toggleRowExpansion(row);
        },

        /* 图片上传时，进行判断转码 */
        uploadFormat(params) {
          //清空显示图片上传列表
          this.$refs.upload.clearFiles();
          const isIMAGE = (params.raw.type === 'image/jpeg' || params.raw.type === 'image/jpg' || params.raw.type === 'image/png');
          const is2M = params.raw.size / 1024 / 1024 <= 2;
          if(!isIMAGE){
            this.$message.error('上传文件只能是图片格式！');
            return false;
          }
          if (!is2M){
            this.$message.error('上传图片大小不能超过2MB！！');
            return false;
          }
          let reader = new FileReader();
          //转换为base64
          reader.readAsDataURL(params.raw);
          let that = this;
          reader.onload = function (e) {
            that.addStudentForm.stuImage = this.result;
            that.editStudentForm.stuImage = this.result;
          }
        },

        /* 添加学生 */
        addStudent() {
          this.$refs.addStudentFormRef.validate(valid => {
            if(!valid) return;
            //学号查重
            this.$axios.get(this.$http+'/collegeManageController/checkStudent?userName='+ this.addStudentForm.userName).then(res => {
              if (res.data.code === 100)
                return this.$message.warning("该学号已存在");
              //截取数据
              this.addStudentForm.classId = this.addStudentForm.classId[2];
              this.addStudentForm.dormitoryId = this.addStudentForm.stuBed[1];
              this.addStudentForm.stuBed = this.addStudentForm.stuBed[2];

              //截取身份证后六位作为密码
              let password = "&" + this.$md5(this.addStudentForm.stuIdentityCardNumber.substring(12));
              this.addStudentForm.stuIdentityCardNumber += password;

              //发送添加请求
              this.$axios.post(this.$http+'/collegeManageController/addStudent',this.addStudentForm).then(res => {
                if (res.data.code === 100)
                  return this.$message.error("添加失败");
                this.$message.success("添加成功");
                this.addStudentDialogVisible = false;
                this.getStudentListLimit();
              }).catch(err => err)
            }).catch(err => {
              this.$message.error("后台异常")
            })

          })
        },

        /* 编辑学生信息 */
        editStudent() {
          //封装数据
           this.editStudentForm.classId = this.editStudentForm.classId[2];
           this.editStudentForm.dormitoryId = this.editStudentForm.stuBed[1];
           this.editStudentForm.stuBed = this.editStudentForm.stuBed[2];
           this.$axios.put(this.$http+'/collegeManageController/editStudent', this.editStudentForm).then(res => {
             if(res.data.code === 300)
               this.$message.warning("该宿舍已满员，请选择其他宿舍");
             else if (res.data.code === 100)
               this.$message.error("修改信息失败");
             this.$message.success("修改信息成功");
             this.getStudentListLimit();
           }).catch(err => {
             this.$message.error("后台异常");
             this.getStudentListLimit();
           })
        },

        /* 删除学生信息 */
        async deleteStudent(row) {
          console.log(row);
          const confirmResult = await this.$confirm('是否删除该学生, 是否继续?', '提示', {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err);
          if (confirmResult !== 'confirm')
            return this.$message.info('已取消删除');
          this.$axios.delete(this.$http+'/collegeManageController/deleteStudent', {
            params:{
              userName: row.userName,
              dormitoryId: row.dormitoryId,
              stuName: row.stuName
            }
          }).then(res => {
            if (res.data.code === 200)
              this.$message.success("删除成功！");
            else if (res.data.code === 100)
              this.$message.error("删除失败！");
            //刷新宿管列表
            this.getStudentListLimit();
          }).catch(err => {
            this.getStudentListLimit();
            return this.$message.warning("异常错误！" + err)
          })
        },

        /*取消提交编辑表单，重置数据*/
        cancelEdit() {
          this.editStudentForm = this.resetEditStudentForm;
        },

        //监听添加管理员对话框的关闭,对内容进行清空
        addStudentDialogClosed() {
         this.$refs.addStudentFormRef.resetFields();
        },

        /* 监听 pageSize 改变的事件 */
        handleSizeChange(newSize) {
          this.queryInfo.pageSize = newSize;
          //每次改变之后，重新获取数据
          this.getStudentListLimit();
        },

        /* 监听 pageNum 改变的事件 */
        handleCurrentChange(newPage) {
          this.queryInfo.pageNum = newPage ;
          //每次改变之后，重新获取数据
          this.getStudentListLimit();
        },
      }
    }
</script>

<style scoped lang="less">
  .searchAndAdd > .el-button {
    width: 90px;
  }
  .labelText {
    color:#99A9BF;
    margin-right: 20px;
  }

  .expandCard {
    width: 58%;
    background-color: #F9F9FA;
    padding: 20px 20px 0 20px;
  }

  .addStudentForm {
    .el-input {
      width: 45%;
    }
    .el-cascader {
      width: 70%;
    }
  }

  table {
    td {
      background-color: #F9F9FA;
    }

  }
</style>
